package com.yinhai.message.implement.dwr.sender;

import java.io.Serializable;

import javax.annotation.Resource;

import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import com.yinhai.core.common.api.config.impl.SysConfig;
import com.yinhai.message.api.vo.TMMessageVo;
import com.yinhai.modules.cluster.api.IMessageChannel;
import com.yinhai.modules.cluster.domian.jgroups.JMessageChannel;

@Component("sendMessageCluster")
@DependsOn("loadTa3Config")
public class SendMessageCluster implements InitializingBean {
	private final static Logger log = LoggerFactory.getLogger(SendMessageCluster.class);
	
	@Resource(name = "dwrMessageSender")
	private DwrMessageSender dwrMessageSender;
	@Resource(name = "webSocketMessageSender")
	private WebSocketMessageSender webSocketMessageSender;

	private final  IMessageChannel<Serializable> cacheChannel = new JMessageChannel(SysConfig.getSysConfig("clusterName","TaMessageCluster") + "DWR",new ReceiverAdapter() {
		@Override
		public void receive(Message msg) {
			// 无效消息
//			byte[] buffers = msg.getBuffer();
//			if (buffers.length < 1) {
//				log.warn("Message is empty.");
//				return;
//			}
			TMMessageVo vo = (TMMessageVo) msg.getObject();
			try {
				if("dwr".equals(SysConfig.getSysConfig("msgSendType"))){
					dwrMessageSender.sendMessage(vo);
				}else{
					webSocketMessageSender.sendMessage(vo);
				}
			} catch (Exception e) {
				log.error("Unable to handle received msg", e);
			}
		}
	});
	
	public  IMessageChannel<Serializable> getChannel(){
		return cacheChannel;
	}
	
	public  void send(TMMessageVo vo){
		try {
			cacheChannel.send(vo);
		} catch (Exception e) {
			log.error("Send dwrCluster Error!",e);
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		getChannel().connect();
	}
}
